define(['vue','axios','manager-box','teacher-box','jquery', 'bootstrap', 'backend', 'table', 'form'], function (Vue,Axios,ManagerBox,TeacherBox, $, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化指引面板的展开/收起功能
            $(document).ready(function() {
                $('#toggleGuide').click(function() {
                    var content = $('#guideContent');
                    var icon = $(this).find('i');
                    if (content.is(':visible')) {
                        content.slideUp();
                        icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
                        $(this).html('<i class="fa fa-chevron-down"></i> 展开');
                    } else {
                        content.slideDown();
                        icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
                        $(this).html('<i class="fa fa-chevron-up"></i> 收起');
                    }
                });
            });
            
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'coursetable/classplant/index?relType=school&table_id='+Config.table_id,
                    add_url: 'coursetable/classplant/add?relType=school&table_id='+Config.table_id,
                    edit_url: 'coursetable/classplant/edit?relType=school&table_id='+Config.table_id,
                    multi_url: 'coursetable/classplant/multi?relType=school&table_id='+Config.table_id,
                    del_url: 'coursetable/classplant/del?relType=school&table_id='+Config.table_id,
                    export_url: 'coursetable/classplant/export?relType=school&table_id='+Config.table_id,
                    table: 'fa_course_table_classplant',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                escape: false,
                pk: 'id',
                sortName: 'id', //要使排序生效，在前面添加 weigh desc, 并且数据表weigh字段不能全为0,controller里$list=...->order前再添加->order("weigh desc")
                search: true,
                searchFields: ['classes_id'],
                searchPlaceholder: '请输入班名',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'classes_id', title: '班级名称',align:'left'},
                        {field: 'subject_lv', title: '教学类型'},
                        {field: 'ocation_type', title: '适合教室'},
                        {field: 'teacher_id', title: '老师'},
                        {field: 'manager_id', title: '管理员'},
                        {field: 'price', title: '学费'},
                        {field: 'num', title: '招生人数'},
                        {field: 'ocourse_count', title: '课节数'},
                        {field: 'classes_per_week', title: '周课数'},
                        {field: 'week', title: '周几'},
                        {field: 'daytime', title: '时段'},
                        {field: 'ocation_id', title: '教室',align:'left'},
                        {field: 'start_date', title: '开始时间',align:'left'},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'detail',
                                    classname: 'btn btn-xs btn-warning btn-click',
                                    icon: 'fa fa-thumb-tack',
                                    click: function (value, row, index) {
                                        Backend.api.open('/coursetable/classroomeplan/edit/planids/'+row.id+'/?classesName='+row.classes_id+'&ref=addtabs', '指定教室', {
                                            max: true,
                                            area: ['90%', '90%'],
                                            offset: 'auto',
                                            callback: function (data) {
                                                Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                            }
                                        });
                                    }
                                }
                            ]
                        }
                    ]
                ]
            });
            table.on('load-success.bs.table', function (e, data) {
                // 绑定导出按钮点击事件
                $(document).on("click",".btn-export", function () {
                    var selectedRows = table.bootstrapTable('getSelections');
                    var ids = [];
                    for (var i = 0; i < selectedRows.length; i++) {
                        ids.push(selectedRows[i].id); // 假设数据中的 id 字段存储的是唯一标识
                    }
                    var exportUrl = $.fn.bootstrapTable.defaults.extend.export_url;
                    if (ids.length > 0) {
                        var idParams = ids.join(',');
                        if (exportUrl.indexOf('?') === -1) {
                            exportUrl += '?ids=' + idParams;
                        } else {
                            exportUrl += '&ids=' + idParams;
                        }
                    }
                    var downloadIframe = $('#download-iframe');
                    if (downloadIframe.length === 0) {
                        downloadIframe = $('<iframe id="download-iframe" style="display: none;"></iframe>');
                        $('body').append(downloadIframe);
                    }
                    downloadIframe.attr('src', "//".exportUrl);
                });
                if($("#message").length > 0){
                    $("#message").html(data.message);
                }
            });
            Table.api.bindevent(table);

            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/index.js';
            document.head.appendChild(script);
        },
        add: function () {
            // 加载日期选择器相关资源
            loadFlatpickrResources();
            
            Vue.component('manager-box', ManagerBox);
            Vue.component('teacher-box', TeacherBox);
            new Vue({
                el: '#app',
                components: {
                },
                data: {
                    leftOptions: Config.leftOptions,
                    rightOptions: Config.rightOptions
                }
            });

            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            
            // 初始化标准化开关控件
            Controller.api.initSwitchControls();
            
            Controller.api.bindevent();
        },
        edit: function () {
            Vue.component('manager-box', ManagerBox);
            Vue.component('teacher-box', TeacherBox);
            new Vue({
                el: '#app',
                components: {
                },
                data: {
                    leftOptions: Config.leftOptions,
                    rightOptions: Config.rightOptions
                }
            });
            var row = JSON.parse($('#row').val());

            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            
            // 初始化标准化开关控件
            Controller.api.initSwitchControls();
            
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            // 初始化标准化开关控件
            initSwitchControls: function () {
                // 标准化开关控件的文本更新
                $('.switch-container input[type="checkbox"]').on('change', function () {
                    var $text = $(this).siblings('.switch-text');
                    if ($(this).is(':checked')) {
                        $text.text('是');
                    } else {
                        $text.text('否');
                    }
                });

                // 初始化文本显示
                $('.switch-container input[type="checkbox"]').each(function () {
                    var $text = $(this).siblings('.switch-text');
                    if ($(this).is(':checked')) {
                        $text.text('是');
                    } else {
                        $text.text('否');
                    }
                });
            },
            // 模拟菜单选中功能
            simulateMenuSelection: function() {
                try {
                    // 显示操作提示
                    if (typeof Layer !== 'undefined') {
                        Layer.msg('正在跳转到课程表列表...', {icon: 1, time: 2000});
                    } else if (typeof Toastr !== 'undefined') {
                        Toastr.success('正在跳转到课程表列表...');
                    }
                    
                    // 检查是否在iframe或弹窗中
                    if (window.parent && window.parent !== window) {
                        // 在iframe中，通过父窗口打开新页面
                        setTimeout(function() {
                            // 尝试在根窗口打开页面
                            if (window.top && window.top !== window) {
                                // 在根窗口中打开页面
                                window.top.location.href = '/coursetable/coursetable?ref=addtabs&infostep=2';
                            } else {
                                // 在父窗口中打开页面
                                window.parent.location.href = '/coursetable/coursetable?ref=addtabs&infostep=2';
                            }
                            
                            // 关闭当前弹窗或iframe
                            if (window.parent.Fast && window.parent.Fast.api && window.parent.Fast.api.close) {
                                window.parent.Fast.api.close();
                            } else if (window.parent.Layer && window.parent.Layer.closeAll) {
                                window.parent.Layer.closeAll();
                            } else {
                                // 尝试关闭当前窗口
                                window.close();
                            }
                        }, 1000);
                    } else {
                        // 不在iframe中，直接跳转
                        setTimeout(function() {
                            window.location.href = '/coursetable/coursetable?ref=addtabs&infostep=2';
                        }, 1000);
                    }
                } catch (e) {
                    console.log('跳转时出错:', e);
                    // 出错时直接跳转
                    window.location.href = '/coursetable/coursetable?ref=addtabs';
                }
            },
            formatter: {//渲染的方法
                url: function (value, row, index) {
                    return '<div class="input-group input-group-sm" style="width:250px;"><input type="text" class="form-control input-sm" value="' + value + '"><span class="input-group-btn input-group-sm"><a href="' + value + '" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-link"></i></a></span></div>';
                },
                ip: function (value, row, index) {
                    return '<a class="btn btn-xs btn-ip bg-success"><i class="fa fa-map-marker"></i> ' + value + '</a>';
                },
                status: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    return '<a class="btn-change text-success" data-url="coursetable/classplant/status" data-confirm="确认切换状态？" data-id="' + row.id + '"><i class="fa ' + (row.status == 0 ||row.status == null ? 'fa-toggle-on fa-flip-horizontal text-gray' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                changeStatus: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    return '<a class="btn-change text-success" data-url="coursetable/classplant/coursetable/classplant/changeStatus" data-confirm="确认切换状态？" data-id="' + row.id + '"><i class="fa ' + (row.status === 0 ? 'fa-toggle-on fa-flip-horizontal text-gray' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
            },
            events: {//绑定事件的方法
                ip: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        var container = $("#table").data("bootstrap.table").$container;
                        var options = $("#table").bootstrapTable('getOptions');
                        //这里我们手动将数据填充到表单然后提交
                        $("form.form-commonsearch [name='ip']", container).val(value);
                        $("form.form-commonsearch", container).trigger('submit');
                        Toastr.info("执行了自定义搜索操作");
                    }
                },
            }
        }
    };
    
    // 加载日期选择器相关资源的函数
    function loadFlatpickrResources() {
        // 加载CSS
        var flatpickrCSS = document.createElement('link');
        flatpickrCSS.rel = 'stylesheet';
        flatpickrCSS.href = '/assets/js/backend/common/flatpickr.min.css';
        document.head.appendChild(flatpickrCSS);
        
        // 加载JavaScript
        var flatpickrJS = document.createElement('script');
        flatpickrJS.src = '/assets/js/backend/common/flatpickr.js';
        document.head.appendChild(flatpickrJS);
        
        // 加载中文语言包
        var zhJS = document.createElement('script');
        zhJS.src = '/assets/js/backend/common/zh.js';
        document.head.appendChild(zhJS);
    }
    
    // 将 simulateMenuSelection 暴露为全局函数
    window.simulateMenuSelection = Controller.api.simulateMenuSelection;
    
    return Controller;
});